<template>
  <div class="cart-container">
    <h2>我的购物车</h2>

    <!-- 购物车列表 -->
    <div class="cart-list">
      <el-skeleton :rows="5" animated v-if="loading" />

      <el-empty description="购物车是空的，快去添加商品吧~" v-else-if="cartData.records.length === 0" />

      <div v-else>
        <el-table :data="cartData.records" style="width: 100%">

          <el-table-column label="商品信息" width="400">
            <template #default="{ row }">
              <div class="product-info" @click="showDetail(row.commodity)">
                <el-image
                    :src="row.commodity.commodityAvatar || 'https://via.placeholder.com/80'"
                    :preview-src-list="[row.commodity.commodityAvatar || 'https://via.placeholder.com/80']"
                    fit="cover"
                    class="product-image"
                />
                <div class="product-detail">
                  <h4 class="product-name">{{ row.commodity.commodityName }}</h4>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="120" align="center">
            <template #default="{ row }">
              <span class="price">¥{{ row.commodity.price.toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="180" align="center">
            <template #default="{ row }">
              <el-input-number
                  v-model="row.number"
                  :min="0"
                  :max="row.commodity.commodityInventory"
                  @change="updateCartItem(row)"
                  size="small"
              />
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120" align="center">
            <template #default="{ row }">
              <span class="total-price">¥{{ (row.commodity.price * row.number).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button
                  type="danger"
                  size="small"
                  @click="removeItem(row.id)"
              >
                移除
              </el-button>
              <el-button
                  type="primary"
                  size="small"
                  @click="goToPay(row)"
              >结算</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="parseInt(cartData.total)"
              :page-sizes="[1, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleChangePageSize"
              @current-change="handleChangePageNum"
          />
        </div>
      </div>
    </div>

    <!-- 商品详情弹窗 -->
    <el-dialog v-model="detailVisible" title="商品详情" width="60%">
      <div v-if="currentCommodity" class="commodity-detail">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-image
                :src="currentCommodity.commodityAvatar || 'https://via.placeholder.com/400'"
                fit="cover"
                class="detail-image"
            />
          </el-col>
          <el-col :span="16">
            <h2>{{ currentCommodity.commodityName }}</h2>
            <el-divider />
            <div class="detail-meta">
              <div class="meta-item">
                <span class="meta-label">价格:</span>
                <span class="meta-value price">¥{{ currentCommodity.price.toFixed(2) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">库存:</span>
                <span class="meta-value">{{ currentCommodity.commodityInventory }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">浏览量:</span>
                <span class="meta-value">{{ currentCommodity.viewNum }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">收藏:</span>
                <span class="meta-value">{{ currentCommodity.favourNum }}</span>
              </div>
            </div>
            <el-divider />
            <div class="detail-description">
              <h3>商品描述</h3>
              <p>{{ currentCommodity.commodityDescription || '暂无描述' }}</p>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>


    <!--订单弹出框--->
    <el-dialog
        v-model="orderInfoDialogVisible"
        title="填写订单信息"
        width="600px"
    >
      <el-form
          ref="formRef"
          :model="orderInfoForm"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="收货地址" prop="address">

          <elui-china-area-dht  @change="onChange"></elui-china-area-dht>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
              v-model="orderInfoForm.address2"
              placeholder="小区/城镇街道号"
          />
        </el-form-item>

        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="orderInfoForm.receiverName" placeholder="请输入收货人姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="receiverPhone">
          <el-input v-model="orderInfoForm.receiverPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="购买数量" prop="buyNumber">
          <el-input-number
              v-model="orderInfoForm.buyNumber"
              :min="1"
              :disabled="true"
              controls-position="right"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="orderInfoForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="orderInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交订单</el-button>
      </span>
      </template>
    </el-dialog>

    <!--支付页面对话框组件-->
    <PaymentDialog
        :visible="paymentDialogVisible"
        :order-data="orderData"
        @update:visible="closePaymentDialog"
        @payment-success="handlePayment"
    >
    </PaymentDialog>
  </div>
</template>

<script setup >
import { ref, computed, onMounted,watch } from 'vue'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import request from "@/utils/request";
import PaymentDialog from '@/components/PaymentDialog/index.vue'

// 响应式数据
const cartData = ref({
  current: 0,
  pages: 0,
  records: [],
  size: 0,
  total: 0
})
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const detailVisible = ref(false)
const currentCommodity = ref(null)

import { EluiChinaAreaDht } from 'elui-china-area-dht'
const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat

// 覆盖区县
const onChange = (e) => {
  const province = chinaData[e[0]]
  const city = chinaData[e[1]]
  const area = chinaData[e[2]]
  console.log(province, city ,area)
  orderInfoForm.value.address1 = province.label + city.label + area.label
  console.log(orderInfoForm.value.address1)
}






//分页方法
const handleChangePageSize = (size) => {
  console.log("size is ", size)
  pageSize.value = parseInt(size)
  fetchCartData()
}
const handleChangePageNum = (page) => {
  console.log("page is ", page)
  currentPage.value = parseInt(page)
  fetchCartData()
}

// 方法
const fetchCartData = async () => {
  loading.value = true
  try {
    const res= await request.post("/api/cart/my/listPage",{
      current: currentPage.value,
      pageSize: pageSize.value
    })
    currentPage.value = parseInt(res.data.current)
    pageSize.value = parseInt(res.data.size)
    console.log("购物车数据 is ", res.data)
    cartData.value = res.data
  } catch (error) {
    ElMessage.error('获取购物车数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}
const showDetail = (commodity) => {
  currentCommodity.value = commodity
  detailVisible.value = true
}

const updateCartItem = async (item) => {
  try {
    console.log("row data is ", item)
    if(item.number < 1){
      ElMessage.error('商品数量不能小于1')
      return
    }
    let updatedItem = {
      id: item.id,//购物车id
      number: item.number //商品数量
    }
    const res= await request.post("/api/cart/update",updatedItem)
    console.log("更新购物车数据 is ", res)

    if(res.code === 200){
      ElMessage.success('购物车更新成功')
    }
  } catch (error) {
    ElMessage.error('更新购物车失败')
    console.error(error)
  }
}

const removeItem = async (id) => {
  try {

    console.log("删除的id is ",id)
    const res=await request.get("/api/cart/removeByIds?ids="+id)
    if(res.code === 200){
      ElMessage.success('删除成功')
      await fetchCartData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

const formRef = ref(null)
const orderInfoDialogVisible = ref(false)
//订单数据
const orderData=ref({})
//加载动画
const openFullScreen = () => {
  return new Promise((resolve) => {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    setTimeout(() => {
      loading.close();
      //@ts-ignore
      resolve(); // 完成Promise
    }, 1000);
  });
};

const paymentDialogVisible = ref(false);

const generateOrder=async(orderInfoForm)=>{
  // 提交购买请求
    try {
      //插入订单数据
      const res = await request.post("/api/commodityOrder/add",orderInfoForm);
      //@ts-ignore
      if (res.code === 200) {
        console.log("订单信息is ",res.data)
        if(res.data.payStatus===0){ //订单生成成功 前往支付
          ElMessage.success("订单"+res.data.id+"创建成功,前往支付页面");
          orderData.value=res.data
          //加载1s动画
          console.log("打开")
          //订单填写页面关闭
          orderInfoDialogVisible.value = false
          await openFullScreen()
          paymentDialogVisible.value=true;
        }
      } else {
        ElMessage.error("系统异常，请稍后再试");
      }
    } catch (error) {
      ElMessage.error("购买失败");
    }finally {
      orderInfoDialogVisible.value = false
    }
}

const closePaymentDialog=()=>{
  paymentDialogVisible.value=false
}
const handlePayment =async () => {
  paymentDialogVisible.value=false
  ElMessage.success("支付完成")
  //从购物车中移除
  await removeItem(cartId.value)
}

const handleSubmit = () => {
  if(orderInfoForm.value.address1 !== "" && orderInfoForm.value.address2 !== ""){
    orderInfoForm.value.address=orderInfoForm.value.address1+orderInfoForm.value.address2
  }
  formRef.value.validate((valid) => {

    if (valid) { // 校验通过
      console.log("订单信息 is ", orderInfoForm.value)
      //生成订单 前往支付
      generateOrder(orderInfoForm.value)
    }
  })
}
//填写信息 生成订单
const orderInfoForm = ref({
  address: '',
  address1: '',
  address2:"",
  receiverPhone: '',
  receiverName: '',
  remark:"",
  buyNumber:0,
  commodityId:""
})
const initOrderInfoForm=()=>{
  orderInfoForm.value={
    address: '',
    receiverPhone: '',
    receiverName: '',
    remark:"",
    buyNumber:0,
    commodityId:""
  }
}
const cartId = ref(0) //购物车id
const goToPay = async (row) => {
  //判断row.number
  if(row.number < 1){
    ElMessage.error('商品数量不能小于1')
    return
  }
 cartId.value = row.id
  initOrderInfoForm()
  orderInfoDialogVisible.value = true
  console.log("结算数据 is ",row)
  console.log("结算的商品的id信息 is ",row.commodity.id)
  orderInfoForm.value.buyNumber=row.number
  orderInfoForm.value.commodityId=row.commodity.id
}

// 初始化
onMounted(() => {
  fetchCartData()
})
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
}

.cart-list {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.product-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.select-all {
  margin-right: auto;
}

.total-info {
  margin: 0 20px;
  font-size: 16px;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: left;
}

/* 商品详情样式 */
.commodity-detail {
  padding: 10px;
}

.detail-image {
  width: 100%;
  border-radius: 4px;
}

.detail-meta {
  margin: 15px 0;
}

.meta-item {
  margin-bottom: 10px;
  display: flex;
}

.meta-label {
  width: 80px;
  color: #999;
}

.meta-value {
  flex: 1;
}

.detail-description h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.detail-description p {
  line-height: 1.6;
  color: #666;
}
</style>
